package com.xsprite.managesys.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xsprite.managesys.log.LogManager;
import com.xsprite.managesys.service.XlsxFileManager;

/**
 * Servlet implementation class DeleteXlsxFilesServlet
 */
public class DeleteXlsxFilesServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.service(req, resp);
		PrintWriter pw = resp.getWriter();
		String userid = req.getSession().getAttribute("userid").toString();
		try{
			String params = queryParam("paras");
			com.alibaba.fastjson.JSONObject jsonObj = JSON.parseObject(params);
			JSONArray fileIds = jsonObj.getJSONArray("deleteFiles");
			deleteFiles(fileIds, userid);
			pw.print("删除excel文件成功!");
		} catch (Exception ex){
			pw.print("删除excel文件失败!");
			LogManager.getInstance().log4j("userid = " + userid + " 删除excel文件失败!" + ex.getMessage());
		} finally{
			pw.flush();
			if(pw != null){
				pw.close();
			}
		}
	}
	
	private void deleteFiles(JSONArray fileIds, String userid) throws IOException{
		for(int i = 0; i < fileIds.size(); i++){
			JSONObject fileId = (JSONObject) fileIds.get(i);
			if(!XlsxFileManager.getInstance().hasFile(fileId.getString("tag"))){
				LogManager.getInstance().log4j("userid = " +  userid + " 文件" + fileId.getString("tag") + "不存在");
				continue;
			}
			XlsxFileManager.getInstance().deleteFile(fileId.getString("tag"), userid);
		}
	}
	
	public String getRequestPayload(HttpServletRequest req) {
		StringBuilder sb = new StringBuilder();
		try {
			BufferedReader reader = req.getReader();
			char[] buff = new char[1024];
			int len;
			while ((len = reader.read(buff)) != -1) {
				sb.append(buff, 0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
}
